package org.hecf.demo.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.hecf.demo.user.entity.User;
import org.hecf.demo.user.mapper.UserMapper;
import org.hecf.demo.user.service.IUserService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service("userService")
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRES_NEW)
    public int insert(User user, JSONObject jsonObject) throws Exception {
        List<Integer> successIds = (List<Integer>) jsonObject.get("success");
        List<Integer> failIds = (List<Integer>) jsonObject.get("fail");
        int i = userMapper.insert(user);
        if(user.getId() == 2){
            failIds.add(user.getId());
            throw  new Exception("111");
        }
        successIds.add(user.getId());
        return i ;
    }

    @Override
    @Transactional(propagation=Propagation.NEVER)
    public JSONObject insert(List<User> users) {
        JSONObject result = new JSONObject();
        List<Integer> successIds = new ArrayList<>();
        List<Integer> failIds = new ArrayList<>();
        result.put("success",successIds);
        result.put("fail",failIds);
        for (int i = 0; i < users.size(); i++) {
            User user=users.get(i);
            try {
//                this.insert(user,result);
                ((IUserService)AopContext.currentProxy()).insert(user,result);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return result;
    }

    @Override
    public int insertSelective(User record) {
        return userMapper.insertSelective(record);
    }

    @Override
    public User selectByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(User record) {
        return userMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(User record) {
        return userMapper.updateByPrimaryKeySelective(record);
    }

    private IUserService getServlce(){
        return org.hecf.demo.util.SpringUtil.getBean(this.getClass());
    }
}
